package com.hxd.tabactivityfragment.base

import android.content.Context
import android.os.Bundle
import android.support.annotation.IdRes
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentActivity
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import org.jetbrains.anko.runOnUiThread
import org.jetbrains.anko.toast

/*
 *  项目名：    Tab+Activity+Fragment
 *  包名：      com.hxd.tabactivityfragment.base
 *  文件名:     BaseFragment
 *  创建者:     HXD
 *  创建时间:   2019/3/7 14:10
 *  描述:       Fragment所有的基类
 */

abstract class BaseFragment : Fragment(){

    // Activity对象
    var mActivity: FragmentActivity? = null
    // 根布局
    private var mRootView: View? = null
    // 是否进行过懒加载
    private var isLazyLoad: Boolean = false
    // Fragment 是否可见
    private var isFragmentVisible: Boolean = false
    // 是否是 replace Fragment 的形式
    private var isReplaceFragment: Boolean = false

    /**
     * 获得全局的，防止使用getActivity()为空
     */
    override fun onAttach(context: Context?) {
        super.onAttach(context)
        this.mActivity = context as FragmentActivity?
    }

    /**
     * 获取Activity，防止出现 getActivity() 为空
     */
    open fun getFragmentActivity(): FragmentActivity? {
        return mActivity
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        init()
    }

    /**
     * fragment初始化
     */
    protected open fun init() {

    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        if (mRootView == null && getLayoutId() > 0) {
            mRootView = inflater.inflate(getLayoutId(), null)
        }
//        val parent = mRootView?.parent as ViewGroup
//        parent?.removeView(mRootView)
        return mRootView
    }

    override fun getView(): View? = mRootView

    /**
     * 是否进行了懒加载
     */
    protected fun isLazyLoad(): Boolean = isLazyLoad

    /**
     * 当前 Fragment 是否可见
     */
    fun isFragmentVisible(): Boolean= isFragmentVisible


    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        if (isReplaceFragment) {
            if (isFragmentVisible) {
                initLazyLoad()
            }
        } else {
            initLazyLoad()
        }
    }

    // replace Fragment时使用，ViewPager 切换时会回调此方法
    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        this.isReplaceFragment = true
        this.isFragmentVisible = isVisibleToUser
        if (isVisibleToUser && view != null) {
            if (!isLazyLoad) {
                initLazyLoad()
            } else {
                // 从不可见到可见
                onRestart()
            }
        }
    }

    /**
     * 初始化懒加载
     */
    private fun initLazyLoad() {
        if (!isLazyLoad) {
            isLazyLoad = true
            initFragment()
        }
    }

    /**
     * 从可见的状态变成不可见状态，再从不可见状态变成可见状态时回调
     */
    private fun onRestart() {
    }

    open fun initFragment() {
        initData()
        initView()
        initListener()

    }

    //数据的初始化
    protected open fun initData(){

    }

    //adapter listener
    protected open fun initListener(){

    }

    //引入布局
    abstract fun getLayoutId(): Int

    //标题栏id
    abstract fun getTitleBarId(): Int

    //初始化控件
    protected open fun initView(){

    }

    /**
     * 根据资源 id 获取一个 View 对象
     */
    protected fun <T : View> findViewById(@IdRes id: Int): T = view!!.findViewById(id)
    protected fun <T : View> findActivityViewById(@IdRes id: Int): T = mActivity!!.findViewById(id)


    protected fun myToast(msg:String){
        context!!.runOnUiThread {
            toast(msg)
        }
    }

    /**
     * 销毁当前 Fragment 所在的 Activity
     */
    fun finish() {
        mActivity?.finish()
    }

    /**
     * 获取系统服务
     */
    fun getSystemService(name: String): Any = mActivity!!.getSystemService(name)

    /**
     * Fragment返回键被按下时回调,默认不拦截按键事件，传递给Activity
     */
    open fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean = false
}